Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
how can I make this code shorter? there're too many "ifs"

So ok, this must be pretty simple, but I just can't get it. Should I create some variables and store parts of code there? Or there's a smarter way? I mean conditions are similar and the logic is similar and I'm not quite sure where to start

const comparator = (a: TimeOff, b: TimeOff): number => {
if (order.sortBy === "status" && order.descending) {
  if (a.state === "DECLINED") {
    return -1;
  }
  if (a.state === "APPROVED") {
    return 1;
  }
  return 0;
}
if (order.sortBy === "status" && !order.descending) {
  if (a.state === "DECLINED") {
    return 1;
  }
  if (a.state === "APPROVED") {
    return -1;
  }
  return 0;
}
if (order.sortBy === "dateFrom" && order.descending) {
  if (new Date(a.date_from) < new Date(b.date_from)) {
    return -1;
  }
  if (new Date(a.date_from) > new Date(b.date_from)) {
    return 1;
  }
  return 0;
}
if (order.sortBy === "dateFrom" && !order.descending) {
  if (new Date(a.date_from) < new Date(b.date_from)) {
    return 1;
  }
  if (new Date(a.date_from) > new Date(b.date_from)) {
    return -1;
  }
  return 0;
}}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

let sign;

if (order.sortBy === "status") {
  // Sign will be -1, 0 or 1 (+ operator converts boolean to number, if false then 0, if true 1)
  sign = +(a.state === "APPROVED") - +(a.state === "DECLINED");    
}

if (order.sortBy === "dateFrom") {
  sign = Math.sign(new Date(a.date_from) < new Date(b.date_from));  
}

return sign * (~~order.descending || -1)
about 4 years ago · Juan Pablo Isaza Relatório

0

const sort = {
  "status": {
    "DECLINED": 1,
    "APPROVED": -1
  },
  "dateFrom":{
    "lessThan": -1,
    "higherThan": 1
  }
}

const comparator = (a, b) => {
  const { sortBy, descending } = order
  const offset = new Date(a.date_from) < new Date(b.date_from) ? "lessThan" : "higherThan"
  const value = sort[sortBy][a.state] || sort[sortBy][offset] || 0

  // multiplying by -1 changes the value from negtive to positive and vice versa
  let result = descending ? value : value * -1
  return result 
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda